package com.king.framework.security.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import com.king.common.constant.CacheConstants;
import com.king.common.constant.Constants;
import com.king.common.exception.AssertHelper;
import com.king.common.exception.ServiceException;
import com.king.common.exception.user.CaptchaException;
import com.king.common.exception.user.CaptchaExpireException;
import com.king.common.exception.user.UserPasswordNotMatchException;
import com.king.common.utils.DateTimeUtil;
import com.king.common.utils.MessageUtils;
import com.king.common.utils.ServletUtils;
import com.king.common.utils.ip.IpUtils;
import com.king.common.utils.redis.RedisUtil;
import com.king.common.utils.text.StringUtils;
import com.king.framework.base.domain.vo.LoginUser;
import com.king.framework.manager.AsyncManager;
import com.king.framework.manager.factory.AsyncFactory;
import com.king.framework.security.context.AuthenticationContextHolder;
import com.king.modules.system.domain.SysUserEntity;
import com.king.modules.system.service.SysConfigService;
import com.king.modules.system.service.SysUserService;

/**
 * 登录校验方法
 * 
 * @author king
 */
@Component
public class SysLoginService {
	@Autowired
	private JwtTokenService jwtTokenService;

	@Resource
	private AuthenticationManager authenticationManager;

	@Autowired
	private RedisUtil redisCache;

	@Autowired
	private SysUserService userService;

	@Autowired
	private SysConfigService configService;

	/**
	 * 登录验证
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @param code
	 *            验证码
	 * @param uuid
	 *            唯一标识
	 * @return 结果
	 */
	public String login(String username, String password, String code, String uuid) {
		boolean captchaEnabled = configService.selectCaptchaEnabled();
		//TODO
		if(System.currentTimeMillis()>1){
			captchaEnabled = false;
		}
		// 验证码开关
		if (captchaEnabled) {
			validateCaptcha(username, code, uuid);
		}
		// 用户验证
		Authentication authentication = null;
		try {
			UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,
					password);
			AuthenticationContextHolder.setContext(authenticationToken);
			// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
			authentication = authenticationManager.authenticate(authenticationToken);
		} catch (Exception e) {
			if (e instanceof BadCredentialsException) {
				AsyncManager.me().execute(AsyncFactory.recordLoginLog(username, Constants.LOGIN_FAIL,
						MessageUtils.message("user.password.not.match")));
				throw new UserPasswordNotMatchException();
			} else {
				AsyncManager.me()
						.execute(AsyncFactory.recordLoginLog(username, Constants.LOGIN_FAIL, e.getMessage()));
				AssertHelper.getInstance().throwException(e.getMessage());
			}
		} finally {
			AuthenticationContextHolder.clearContext();
		}
		AsyncManager.me().execute(AsyncFactory.recordLoginLog(username, Constants.LOGIN_SUCCESS,
				MessageUtils.message("user.login.success")));
		LoginUser loginUser = (LoginUser) authentication.getPrincipal();
		recordLoginlog(loginUser.getUserId());
		// 生成token
		return jwtTokenService.createToken(loginUser);
	}

	/**
	 * 校验验证码
	 * 
	 * @param username
	 *            用户名
	 * @param code
	 *            验证码
	 * @param uuid
	 *            唯一标识
	 * @return 结果
	 */
	public void validateCaptcha(String username, String code, String uuid) {
		String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
		String captcha = redisCache.getCacheObject(verifyKey);
		redisCache.deleteObject(verifyKey);
		if (captcha == null) {
			AsyncManager.me().execute(AsyncFactory.recordLoginLog(username, Constants.LOGIN_FAIL,
					MessageUtils.message("user.jcaptcha.expire")));
			throw new CaptchaExpireException();
		}
		if (!code.equalsIgnoreCase(captcha)) {
			AsyncManager.me().execute(AsyncFactory.recordLoginLog(username, Constants.LOGIN_FAIL,
					MessageUtils.message("user.jcaptcha.error")));
			throw new CaptchaException();
		}
	}

	/**
	 * 记录登录信息
	 *
	 * @param userId
	 *            用户ID
	 */
	public void recordLoginlog(Long userId) {
		SysUserEntity sysUser = new SysUserEntity();
		sysUser.setId(userId);
		sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
		sysUser.setLoginDate(DateTimeUtil.getNowDate());
		userService.updateUserProfile(sysUser);
	}
}
